package com.yf.dxapp.module.app.component.app;

import cn.hutool.core.net.url.UrlBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yf.dxapp.module.app.controller.app.vo.ChatVO;
import com.yf.dxapp.module.app.controller.app.vo.FullChatVO;
import com.yf.dxapp.module.app.dal.dataobject.appconfig.AppConfigDO;
import com.yf.dxapp.module.app.dal.dataobject.appuser.AppUserDO;
import com.yf.dxapp.module.app.service.appconfig.AppConfigService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
public class AppCustomerServiceComponent {

    @Resource
    private AppConfigService appConfigService;

    public FullChatVO getCustomerServiceInfo(AppUserDO loginUser) {
        if (loginUser == null) {
            return null;
        }
        List<AppConfigDO> appConfigs = appConfigService.findConfigByKey(Arrays.asList("企微客服配置", "在线客服配置"));
        FullChatVO fullChatVO = new FullChatVO();
        String weixinWorkConfigStr = appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "企微客服配置"))
                .map(AppConfigDO::getValue)
                .findFirst().orElse("");
        if (StringUtils.isNotBlank(weixinWorkConfigStr)) {
            fullChatVO.setWeixinWorkChat(JSON.parseObject(weixinWorkConfigStr, ChatVO.class));
        }
        String onlineChatConfigStr = appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "在线客服配置"))
                .map(AppConfigDO::getValue)
                .findFirst().orElse("");
        if (StringUtils.isNotBlank(onlineChatConfigStr)) {
            ChatVO onlineChat = JSON.parseObject(onlineChatConfigStr, ChatVO.class);
            JSONObject user = new JSONObject();
            user.put("名称", loginUser.getName());
            user.put("手机", loginUser.getMobile());
            UrlBuilder urlBuilder = UrlBuilder.of(onlineChat.getChatUrl()).addQuery("uniqueId", loginUser.getId().toString()).addQuery("customer", user.toJSONString());
            onlineChat.setChatUrl(urlBuilder.build());
            fullChatVO.setOnlineChat(onlineChat);
        }
        return fullChatVO;
    }

}
